<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
		<meta name="format-detection" content="telephone=no" />
		<title>聊天</title>
		<link rel="stylesheet" type="text/css" href="../../css/api.css"/>
		<link rel="stylesheet" type="text/css" href="../../css/aui.css" />
		<link rel="stylesheet" type="text/css" href="../../css/aui-flex.css" />
		<style>
			.aui-content-padded {
				margin: 0 10px;
				padding: 10px 0;
			}
			.aui-content-padded.hasItem{
				padding-top: 160px;
			}
			.time {
				text-align: center;
			}
			.time span{
				background: #ccc;
				color:#fff;
				padding:2px 5px;
				margin-bottom: 8px;
				display: inline-block;
				font-size: 12px;
				border-radius: 3px;
			}
			.clear {
				clear: both;
			}
			.aui-chat-receiver .aui-chat-receiver-cont,
			.aui-chat-sender .aui-chat-sender-cont{
				/*max-width: 80% !important;*/
			}
			.bg-white{
				background: #fff !important;
			}
			.bg-white-tri{
				border-color:transparent transparent transparent #fff;
			}
		</style>
	</head>
	<body>
		<div id="isRecording" style="position: fixed;left:50%;bottom:150px;z-index: 9999;display: none;">
			<div style="width: 100px;height:100px;left:-50px;position:relative;background: rgba(179,179,179,0.8);border-radius: 10px;color:#fff;text-align: center;box-shadow: 0 0 10px #eee;">
				<i class="aui-iconfont aui-icon-notification" style="display: inline-block;font-size: 50px;"></i>
				<div style="margin-top: -10px;"><b class="desc">正在录音</b></div>
			</div>
		</div>
		<div class="aui-content-padded" id="messageList">
		</div>
	</body>
	<script id="item-template" type="text/x-dot-template">
		<div class="aui-content" id="item-info" style="position: fixed;top:0;left:0;width: 100%;z-index: 9999;">
			<ul class="aui-list-view">
				<li class="aui-list-view-cell aui-img">
					<div class="aui-arrow-right" onclick="go2Pro({{=it.itemid}},'../')">
						<div class="aui-img-object aui-pull-left" style="width: 100%;">
							<div style="background-size: cover;width: 100%;height:100%;background-image: url({{=it.thumb}});"></div>
						</div>
						<div class="aui-img-body">
							<div class="aui-ellipsis-1">{{=it.title}}</div>
							<h4 style="color:#666;">¥{{=it.price}}</h4>
							<p style="font-size: 12px;">成交{{=it.wholesale_num}}笔</p>
						</div>
					</div>
				</li>
				<li class="aui-list-view-cell aui-text-center">
					<span class="aui-btn aui-btn-info aui-btn-outlined" style="padding-left:20px;padding-right: 20px;" onclick="sendItemLink({{=it.itemid}},'{{=it.thumb}}','{{=it.title}}','{{=it.price}}','')">发送链接</span>
					<i class="aui-iconfont aui-icon-close " style="position: absolute;right:0px;top:5px;padding: 8px;font-size: 20px;color:#bbb;" onclick="closeItem();"></i>
				</li>
			</ul>
		</div>
	</script>
	<script id="chatitem-template" type="text/x-dot-template">
		<div class="aui-content aui-clearfix" id="item-info" style="width: 100%;margin:0;" tapmode>
			<ul class="aui-list-view" style="margin:0;padding: 0;"  onclick="go2Pro({{=it.itemid}},'../')">
				<li class="aui-list-view-cell" style="padding: 0;">
					<div style="background-size: cover;width: 100%;height:120px;background-image: url({{=it.thumb}});"></div>
				</li>
				<li class="aui-list-view-cell" style="padding-bottom: 0;">
					<div class="aui-img-body" style="color:#666;font-size: 14px;">
					{{=it.title}}
					</div>
				</li>
			</ul>
		</div>
	</script>
	<script type="text/javascript" src="../../script/api.js"></script>
	<script type="text/javascript" src="../../script/common.js"></script>
	<script type="text/javascript" src="../../script/zepto.min.js"></script>
	<script type="text/javascript" src="../../script/doT.min.js"></script>
	<script type="text/javascript" src="../../script/jquery-1.11.3.js"></script>
	<script type="text/javascript">
		var userId, chatBox, portraitUri,targetName, sourcePath = "widget://image/emotion", //表情存放目录
		emotionData, imagePath, timeRecord = 0, height, myAvatar,itemid;
		var errorSentTag='<span class="sentError aui-pull-right" onclick="resentMsg();"><i class="aui-iconfont aui-text-danger aui-icon-warnfill" style="display:inline-block;font-size:30px;margin-right:-5px;"></i></span>';
		//存储表情;
		apiready = function() {
			var frameName = api.frameName;
			userId = api.pageParam.key;
			portraitUri = api.pageParam.key1;
			targetName=api.pageParam.key2;
			isTargetCompany=api.pageParam.key3;
			itemid=api.pageParam.key4;

			//清空消息数
			var chatContent=$api.getStorage('chatContent');
			if(chatContent){
				for(i in chatContent){
					if(chatContent[i].senderUserId==userId&&chatContent[i].unreadCount>0){
						chatContent[i].unreadCount=0;

						//发送清楚消息数通知
						api.sendEvent({
							name:'clearChatUserCount',
							extra: {
								userId: userId
							}
						});

						break;
					}
				}
				$api.setStorage('chatContent',chatContent);
			}

			// myAvatar = 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png';

			getStorageAll();
			myAvatar=head_pic;
			
			height = api.frameHeight;
			//表情图片处理
			getImgsPaths(sourcePath, function(emotion) {
				emotionData = emotion;
			});
			getHistoryMessages();
			swipeLeft();
			//监听发送的新消息是否完成
			api.addEventListener({
				name : 'backSendMessageSuccess'
			}, function(ret) {
				if (ret && ret.value) {
					if ($api.byId("messageStatus-" + ret.value.messageId)) {
						$api.remove($api.byId("messageStatus-" + ret.value.messageId));
					}
				}
			})
			chatBox = api.require('UIChatBox');
			openChatBox();
			//监听键盘聊天框键盘弹出,用于调整聊天窗口高度
			chatBox.addEventListener({
				target : 'inputBar',
				name : 'move'
			}, function(ret, err) {
				if (ret.panelHeight > 0) {
					api.setFrameAttr({
						name : 'chat_frm',
						rect : {
							h : height - ret.panelHeight
						}
					});
				} else {
					api.setFrameAttr({
						name : 'chat_frm',
						rect : {
							h : height
						}
					});
				}
				setTimeout(function() {
					window.scrollTo(0, $api.offset($api.byId("messageList")).h);
				}, 200)
			});
			//监听按下录音
			chatBox.addEventListener({
				target : 'recordBtn',
				name : 'press'
			}, function(ret, err) {
				$('#isRecording').show();
				api.startRecord({
					//path: 'fs://1.amr'
				});
			});
			//监听松开录音键
			chatBox.addEventListener({
				target : 'recordBtn',
				name : 'press_cancel'
			}, function(ret, err) {
				//松开后停止录音
				$('#isRecording').hide();
				$('#isRecording .desc').text('正在录音');
				api.stopRecord(function(ret, err) {
					//api.alert({msg:('文件路径--'+ret.path+';录音时长:'+ret.duration+'s')});
					if (ret && ret.duration > 0) {
						api.sendEvent({
							name : 'sendMessage',
							extra : {
								targetId : userId,
								objectName : 'RC:VcMsg',
								conversationType : 'PRIVATE',
								message : ret
							}
						})
					}
				});
			});

			//监听松开录音键
			chatBox.addEventListener({
				target : 'recordBtn',
				name : 'move_out'
			}, function(ret, err) {
				$('#isRecording .desc').text('上滑取消')
			});

			//监听松开录音键
			chatBox.addEventListener({
				target : 'recordBtn',
				name : 'move_in'
			}, function(ret, err) {
				$('#isRecording .desc').text('正在录音')
			});

			//监听松开录音键
			chatBox.addEventListener({
				target : 'recordBtn',
				name : 'move_out_cancel'
			}, function(ret, err) {
				//松开后停止录音
				$('#isRecording').hide();
				$('#isRecording .desc').text('正在录音');
			});

			if(itemid){
				var url = 'mall/index/goodsId/' + itemid + /userid/ + user_id;
				ajaxRequest(url, 'get', {}, function (ret, err) {
					if (ret.status == 1) {
						itemData=ret.msg;
						var tpl = $api.byId('item-template').text;
                        var tempFn = doT.template(tpl);
                        $('body').prepend(tempFn(ret.msg));

						$('#messageList').addClass('hasItem');
					}else{
						api.toast({
							msg: ret.msg,
							duration: 2000,
							location: 'bottom'
						});
					}
				})
			}
		}

		//监听获取消息
		function getNewMessages(str) {
			if (str) {
				var ret = {};
				ret['value'] = JSON.parse(str);
				//如果当前消息的目标id等于当前会话目标id，写入，否则状态栏提醒
				if (ret.value.message.targetId == userId) {
					var now = Date.now();
					var time = new Date().toLocaleTimeString();
					var html = '';
					html += '<div class="clear"></div>'
					html += (now - timeRecord) / 1000 > 180 ? '<div class="time"><span class="timespan">' + time + '</span></div>' : '';
					html += '<div class="aui-chat-receiver" id="message-' + ret.value.message.messageId + '">';
					var Avatar = portraitUri == '' || portraitUri == undefined ? '../image/noavatar.gif' : portraitUri;
					html += '<div class="aui-chat-receiver-avatar"><img onclick="detail(' + userId + ',\'' + portraitUri + '\')" src="' + Avatar + '"></div>';
					html += '<div class="aui-chat-receiver-cont '+(ret.value.message.objectName=='RC:ImgTextMsg'?'bg-white':'')+'">';
					html += '<div class="aui-chat-left-triangle '+(ret.value.message.objectName=='RC:ImgTextMsg'?'bg-white-tri':'')+'"></div>';
					timeRecord = now;
					switch(ret.value.message.objectName) {
						//文字消息
						case 'RC:TxtMsg':
							html += '<span>' + transText(ret.value.message.content.text) + '</span>';
							break;
						//图片消息
						case 'RC:ImgMsg':
							html += '<span class="aui-chat-img chat-img"><img src="' + ret.value.message.content.imageUrl + '" onclick="getPic(this)"/></span>';
							break;
						//语音消息
						case 'RC:VcMsg':
							//alert(JSON.stringify(ret.value.message.content));
							html += '<div class="aui-chat-status">' + ret.value.message.content.duration + 's</div>';
							html += '<span tapmode onclick="playVoice(\'' + ret.value.message.content.voicePath + '\',\'' + ret.value.message.messageId + '\')" ><i class="aui-iconfont aui-icon-sound" id="messageVoice-' + ret.value.message.messageId + '"></i></span>';
							break;
						//图文消息
						case 'RC:ImgTextMsg':
							var rowData=ret.value.message;
							if(rowData.content.extra=='item'){
								var tpl = $api.byId('chatitem-template').text;
								var tempFn = doT.template(tpl);
								var itemData={itemid:rowData.content.description,title:rowData.content.title,thumb:rowData.content.imageUrl};
								html+=$(tempFn(itemData)).html();

							}else{
								html+= '<span>[图文消息]</span>';
							}
							break;
						//位置消息
						case 'RC:LBSMsg':
							html += '<span class="aui-chat-img"><img src="http://api.map.baidu.com/staticimage?center=' + ret.value.message.content.longitude + ',' + ret.value.message.content.latitude + '&width=300&height=180&zoom=15&copyright=1" /></span>';
							html += '<p>' + ret.value.message.content.poi + '</p>';
							break;
					}
					html += '</div>';
					html += '</div>';
					$api.append($api.byId("messageList"), html);
					api.parseTapmode();
					setTimeout(function() {
						window.scrollTo(0, $api.offset($api.byId("messageList")).h);
					}, 100)
				}
			}
		}

		function errorSendMessage(messageId){
			var $msgRow=$('#message-'+messageId)
			if($msgRow.length){
				$msgRow.find('.aui-chat-sender-cont').after(errorSentTag);
			}
		}

		//监听发送消息
		function backSendMessage(str) {
			if (str) {
				//alert(ret.value.message.content.thumbPath);
				ret = {};
				ret['value'] = JSON.parse(str);
				//如果当前消息的目标id等于当前会话目标id，写入，否则状态栏提醒
				//alert(ret.value.message.targetId+','+userId);
				if (ret.value.message.targetId == userId) {
					var time = new Date().toLocaleTimeString();
					var now = Date.now();
					var html = '';
					html += '<div class="clear"></div>'
					html += (now - timeRecord) / 1000 > 180 ? '<div class="time"><span class="timespan">' + time + '</span></div>' : '';
					html += '<div class="aui-chat-sender" id="message-' + ret.value.message.messageId + '">';
					var Avatar = myAvatar == '' || myAvatar == undefined ? '../image/noavatar.gif' : myAvatar;
					html += '<div class="aui-chat-sender-avatar"><img src="' + Avatar + '"></div>';
					html += '<div class="aui-chat-sender-cont '+(ret.value.message.objectName=='RC:ImgTextMsg'?'bg-white':'')+'">';
					html += '<div class="aui-chat-right-triangle '+(ret.value.message.objectName=='RC:ImgTextMsg'?'bg-white-tri':'')+'"></div>';
					timeRecord = now;
					switch(ret.value.message.objectName) {
						//文字消息
						case 'RC:TxtMsg':
							html += '<span>' + transText(ret.value.message.content.text) + '</span>';
							break;
						//图片消息
						case 'RC:ImgMsg':
							// html += '<div class="aui-chat-status chat-img" id="messageStatus-' + ret.value.message.messageId + '"><i class="aui-iconfont aui-icon-loading aui-chat-progress"></i></div>';
							html += '<span class="aui-chat-img"><img src="' + imagePath + '" onclick="getPic(this)"/></span>';
							break;
						//语音消息
						case 'RC:VcMsg':
							//                        	alert(JSON.stringify(ret.value.message.content));
							html += '<div class="aui-chat-status">' + ret.value.message.content.duration + 's</div>';
							html += '<span tapmode onclick="playVoice(\'' + ret.value.message.content.voicePath + '\',\'' + ret.value.message.messageId + '\')"><i class="aui-iconfont aui-icon-sound" id="messageVoice-' + ret.value.message.messageId + '"></i></span>';
							break;
						//图文消息
						case 'RC:ImgTextMsg':
							var rowData=ret.value.message;
							if(rowData.content.extra=='item'){
								var tpl = $api.byId('chatitem-template').text;
								var tempFn = doT.template(tpl);
								var itemData={itemid:rowData.content.description,title:rowData.content.title,thumb:rowData.content.imageUrl};
								html+=$(tempFn(itemData)).html();

							}else{
								html+= '<span>[图文消息]</span>';
							}
							break;
					}
					html += '</div>';
					html += '</div>';
					$api.append($api.byId("messageList"), html);
					api.parseTapmode();
					window.scrollTo(0, $api.offset($api.byId("messageList")).h);
				}
			}
		}

		//获取历史消息
		function getHistoryMessages() {
			//通过sendEvent方法从message_list中获取当前会话历史消息,发送目标id，消息类型，最后一条id
			//alert(userId);
			api.sendEvent({
				name : 'getHistoryMessages',
				extra : {
					targetId : userId,
					type : 'PRIVATE'
				}
			});
			//监听获取历史消息
			api.addEventListener({
				name : 'backHistoryMessages'
			}, function(ret) {
				//alert(JSON.stringify(ret.value.message));
				if (ret && ret.value.message) {

					getStorageAll();
					var myUserid = user_id;  //动态获取当前用户
					if (ret.value.message.length) {
						var messageList = ret.value.message.sort(getSortFun('asc', 'sentTime'));
						var html = '';
						for (var i in messageList) {
							//alert(messageList.length);
							var before = new Date(messageList[i].sentTime);
							//历史日期
							var beDate = before.toLocaleDateString();
							//现在日期
							var now = new Date().toLocaleDateString();
							var time = beDate == now ? before.toLocaleTimeString() : before.toLocaleString();
							if (messageList[i].senderUserId == myUserid) {
								//当前发送用户
								html += '<div class="clear"></div>'
								html += (messageList[i].sentTime - timeRecord) / 1000 > 180 ? '<div class="time"><span class="timespan">' + time + '</span></div>' : '';
								html += '<div class="aui-chat-sender" id="message-' + messageList[i].messageId + '">';
								var Avatar = myAvatar == '' || myAvatar == undefined ? '../image/noavatar.gif' : myAvatar;
								html += '<div class="aui-chat-sender-avatar"><img src="' + Avatar + '"></div>';
								html += '<div class="aui-chat-sender-cont '+(messageList[i].objectName=='RC:ImgTextMsg'?'bg-white':'')+'">';
								html += '<div class="aui-chat-right-triangle '+(messageList[i].objectName=='RC:ImgTextMsg'?'bg-white-tri':'')+'"></div>';
							} else {
								html += '<div class="clear"></div>'
								html += (messageList[i].sentTime - timeRecord) / 1000 > 180 ? '<div class="time"><span class="timespan">' + time + '</span></div>' : '';
								html += '<div class="aui-chat-receiver" id="message-' + messageList[i].messageId + '">';
								var Avatar = portraitUri == '' || portraitUri == undefined ? '../image/noavatar.gif' : portraitUri;
								html += '<div class="aui-chat-receiver-avatar"><img  onclick="detail(' + userId + ',\'' + portraitUri + '\')" src="' + Avatar + '"></div>';
								html += '<div class="aui-chat-receiver-cont '+(messageList[i].objectName=='RC:ImgTextMsg'?'bg-white':'')+'">';
								html += '<div class="aui-chat-left-triangle '+(messageList[i].objectName=='RC:ImgTextMsg'?'bg-white-tri':'')+'"></div>';
							}

							timeRecord = messageList[i].sentTime;
							switch(messageList[i].objectName) {
								//文字消息
								case 'RC:TxtMsg':
									html += '<span>' + transText(messageList[i].content.text) + '</span>';
									break;
								//图片消息
								case 'RC:ImgMsg':
									html += '<span class="aui-chat-img chat-img"><img src="' + messageList[i].content.imageUrl + '" onclick="getPic(this)"/></span>';
									break;
								//语音消息
								case 'RC:VcMsg':
									//html += '<span>[语音消息]</span>';
									html += '<div class="aui-chat-status">' + messageList[i].content.duration + 's</div>';
									html += '<span tapmode onclick="playVoice(\'' + messageList[i].content.voicePath + '\',\'' + messageList[i].messageId + '\')"><i class="aui-iconfont aui-icon-sound" id="messageVoice-' + messageList[i].messageId + '"></i></span>';
									break;
								//图文消息
								case 'RC:ImgTextMsg':
									var rowData=messageList[i];
									if(rowData.content.extra=='item'){
										var tpl = $api.byId('chatitem-template').text;
										var tempFn = doT.template(tpl);
										var itemData={itemid:rowData.content.description,title:rowData.content.title,thumb:rowData.content.imageUrl};
										html+=$(tempFn(itemData)).html();

									}else{
										html += '<span>[图文消息]</span>';
									}
									break;
							}
							html += '</div>';
							if(messageList[i].sentStatus=='FAILED')html+=errorSentTag;
							html += '</div>';
						}
						$api.prepend($api.byId("messageList"), html);
						api.parseTapmode();
						setTimeout(function() {
							window.scrollTo(0, $api.offset($api.byId("messageList")).h);
						}, 300)
					}else{
						//没有历史消息
					}
					if (ret.value.message.length<30){
						if(isTargetCompany){
							//公司聊天
							$('#messageList').prepend('<div id="emptyMsg"><div class="clear"></div>'+
								'<div class="aui-chat-receiver">'+
								'<div class="aui-chat-receiver-avatar" onclick="go2User('+userId+',\'../\')"><img src="'+portraitUri+'"></div>'+
								'<div class="aui-chat-receiver-cont">'+
							// '<div class="aui-chat-left-triangle"></div>您好，我是东东贸易公司，欢迎咨询<img src="../../image/emotion/Expression_1.png" '+
							// 'width="24" height ="24" />'+
							'<div class="aui-chat-left-triangle"></div>您好，我是'+targetName+'，有什么能帮到您呢？'+
							'</div></div></div>')
						}else{
							//个人聊天
							$('#messageList').prepend('<div id="emptyMsg><div class="clear"></div><div class="time"><span class="timespan">您已开启和'+targetName+'的会话</span></div></div>');

						}
					}
				} else {
				}
			});
		}

		//播放语音
		function playVoice(voicePath, messageId) {
			$api.addCls($api.byId("messageVoice-" + messageId), 'aui-text-warning');
			api.startPlay({
				path : voicePath
			}, function() {
				$api.removeCls($api.byId("messageVoice-" + messageId), 'aui-text-warning');
			});
		}

		//排序函数
		function getSortFun(order, sortBy) {
			var ordAlpah = (order == 'asc') ? '>' : '<';
			var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?1:-1');
			return sortFun;
		}

		//表情处理
		function transText(text, imgWidth, imgHeight) {
			var imgWidth = imgWidth || 24;
			var imgHeight = imgHeight || 24;
			var regx = /\[(.*?)\]/gm;
			var textTransed = text.replace(regx, function(match) {
				if (emotionData == undefined) {
					var imgSrc = '';
				} else {
					var imgSrc = emotionData[match];
				}
				if (!imgSrc) {/* 说明不对应任何表情,直接返回即可.*/
					return match;
				}
				var img = "<img src='" + imgSrc + "' width='" + imgWidth + "' height ='" + imgHeight + "' />";
				return img;
			});
			return textTransed;
		}

		/*获取所有表情图片的名称和真实URL地址，以JSON对象形式返回。其中以表情文本为 属性名，以图片真实路径为属性值*/
		function getImgsPaths(sourcePathOfChatBox, callback) {
			var jsonPath = sourcePathOfChatBox + "/emotion.json";
			//表情的JSON数组
			api.readFile({
				path : jsonPath
			}, function(ret, err) {
				if (ret.status) {
					var emotionArray = JSON.parse(ret.data);
					var emotion = {};
					for (var i in emotionArray) {
						var emotionItem = emotionArray[i];
						var emotionText = emotionItem["text"];
						var emotionUrl = "../../image/emotion/" + emotionItem["name"] + ".png";
						emotion[emotionText] = emotionUrl;
					}
					/*把emotion对象 回调出去*/
					if ("function" === typeof (callback)) {
						callback(emotion);
					}
				}
			});
		}

		function openChatBox() {
			chatBox.open({
				placeholder : '',
				maxRows : 4,
				emotionPath : 'widget://image/emotion',
				texts : {
					recordBtn : {
						normalTitle : '按住 说话',
						activeTitle : '松开 结束'
					}
				},
				styles : {
					inputBar : {
						borderColor : '#d9d9d9',
						bgColor : '#f2f2f2'
					},
					inputBox : {
						borderColor : '#B3B3B3',
						bgColor : '#FFFFFF'
					},
					emotionBtn : {
						normalImg : 'widget://image/chatBox/face1.png'
					},
					extrasBtn : {
						normalImg : 'widget://image/chatBox/add1.png'
					},
					keyboardBtn : {
						normalImg : 'widget://image/chatBox/key1.png'
					},
					speechBtn : {
						normalImg : 'widget://image/chatBox/key3.png'
					},
					recordBtn : {
						normalBg : '#fff',
						activeBg : '#ccc',
						color : '#666',
						size : 14
					},
					indicator : {
						target : 'both',
						color : '#c4c4c4',
						activeColor : '#9e9e9e'
					}
				},
				extras : {
					titleSize : 10,
					titleColor : '#a3a3a3',
					btns : [{
						title : '图片',
						normalImg : 'widget://image/chatBox/album1.png',
						activeImg : 'widget://image/chatBox/album2.png'
					}, {
						title : '拍照',
						normalImg : 'widget://image/chatBox/cam1.png',
						activeImg : 'widget://image/chatBox/cam2.png'
					}]
				}
			}, function(ret) {
				//点击附加功能面板
				if (ret.eventType == 'clickExtras') {
					//alert("用户点击了第"+ ret.index +"个按钮");
					if (ret.index == 0) {
						//图片
						api.getPicture({
							sourceType : 'library',
							encodingType : 'jpg',
							mediaValue : 'pic',
							destinationType : 'url',
							allowEdit : true,
							quality : 70,
							targetWidth : 320,
							saveToPhotoAlbum : false
						}, function(ret, err) {
							if (ret) {
								api.sendEvent({
									name : 'sendMessage',
									extra : {
										targetId : userId,
										objectName : 'RC:ImgMsg',
										conversationType : 'PRIVATE',
										message : ret.data,
										isCompany:isTargetCompany
									}
								});
								imagePath = ret.data;
							}
						});
					} else if (ret.index == 1) {
						//图片
						api.getPicture({
							sourceType : 'camera',
							encodingType : 'jpg',
							mediaValue : 'pic',
							destinationType : 'url',
							allowEdit : true,
							quality : 70,
							targetWidth : 640,
							saveToPhotoAlbum : false
						}, function(ret, err) {
							if (ret) {
								api.sendEvent({
									name : 'sendMessage',
									extra : {
										targetId : userId,
										objectName : 'RC:ImgMsg',
										conversationType : 'PRIVATE',
										message : ret.data,
										isCompany:isTargetCompany
									}
								});
								imagePath = ret.data;
							}
						});
					} else if (ret.index == 2) {
						
					}
				}
				//点击发送按钮
				if (ret.eventType == 'send' && ret.msg) {
					//通过sendEvent将发送内容广博，消息页面接收并广播回来
					//单聊文字消息类型
					api.sendEvent({
						name : 'sendMessage',
						extra : {
							targetId : userId,
							objectName : 'RC:TxtMsg',
							conversationType : 'PRIVATE',
							message : $.trim(ret.msg),
							isCompany:isTargetCompany
						}
					})
					//alert('输入的内容是：'+ transText(ret.msg));
				}
			});
		};
		function swipeLeft() {
			if (!(/android/gi).test(navigator.appVersion)) {
				api.addEventListener({
					name : 'swiperight'
				}, function(ret, err) {
					// api.execScript({
					// 	name : 'root',
					// 	script : 'initial();'
					// });
					api.closeWin();
				});
			}
		}

		//图片发大
		function getPic(img) {
			//alert(111)
			var photosArr = [];
			var src = $api.attr(img, 'src');
			photosArr.push(src);

			api.openWin({
				name: 'photobrowser_win',
				url: '../friend/photobrowser_win.html',
				animation:{
					type:"fade",               
					duration:200
				},
				pageParam:{
					imgList:photosArr
				}
			});

			// var obj = api.require('imageBrowser');
			// obj.openImages({
			// 	imageUrls : photosArr,
			// 	showList : false,
			// 	activeIndex : 0
			// });
		}

		function detail(id, img) {
			// alert(img);
			go2User(id,'../');
		}


		function closeItem(){
			$('#item-info').hide();
			$('#messageList').removeClass('hasItem');
		}

		function sendItemLink(itemid,itemThumb,itemTitle,itemPrice,itemSale){
			api.sendEvent({
				name : 'sendMessage',
				extra : {
					targetId : userId,
					objectName : 'RC:ImgTextMsg',
					conversationType : 'PRIVATE',
					message : {
						title: itemTitle,
						description: itemid,
						imageUrl: itemThumb,
						extra: 'item',
						url: ''
					},
					isCompany:isTargetCompany
				}
			});
			closeItem();
		}

		function resentMsg(){
			api.toast({msg:'发送失败'})
		}
	</script>
</html>